package com.googlecode.cswish.struts.hibernate;

import javax.persistence.Entity;
import javax.persistence.Table;

import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;

import com.googlecode.cswish.struts.ContextHolder;


public class HibernateUtil {

	public static Object unproxy(Object object) {
		if (object instanceof HibernateProxy) {
			HibernateProxy proxy = (HibernateProxy) object;
			LazyInitializer li = proxy.getHibernateLazyInitializer();
			return li.getImplementation();
		}
		else {
			return object;
		}
	}
	
	public String getTableName(Class entityClass) {
		Table table = (Table) entityClass.getAnnotation(Table.class);
		if (table != null) {
			return table.name();
		}
		
		Class parentClass = entityClass.getSuperclass();
		Entity entity = (Entity) parentClass.getAnnotation(Entity.class);
		while (entity == null && parentClass != Object.class) {
			parentClass = parentClass.getSuperclass();
			entity = (Entity) parentClass.getAnnotation(Entity.class);
		}
		
		// see CustomNamingStrategy
		if (entity != null) {
			return  (ContextHolder.get().getSiteName() + '_' + parentClass.getSimpleName()).toLowerCase();
		} else {
			return (ContextHolder.get().getSiteName() + '_' + entityClass.getSimpleName()).toLowerCase();
		}
	}
}
